package com.hanhai.zrb.api.mongodb;

import java.util.List;

import org.apache.log4j.Logger;

import com.hanhai.zrb.model.project.ProjectDetail;

public class ProjectDetailClient {
	//private ProjectDetailHbaseClient hbase = new ProjectDetailHbaseClient();
	private ProjectDetailMongodbClient mongodb = new ProjectDetailMongodbClient();
	private Logger log = Logger.getLogger(getClass());

	// 2个都增加
	public void add(ProjectDetail projectDetail) {
		//log.info("Add ProjectDetail for hbase.");
		//hbase.insertProjectDetail(projectDetail);
		log.info("Add ProjectDetail for mongodb.");
		mongodb.add(projectDetail);
	}

	// 2个都更新
	public void update(ProjectDetail projectDetail) {
		if (projectDetail.getId() == null) {
			log.error("ProjectDetail is is null,Cantnot update~");
			return;
		}
		Long id = projectDetail.getId();
	
		ProjectDetail one = mongodb.get(id);
		// Mongodb，如果存在，更新
		if (one != null) {
			log.info("Update ProjectDetail,Mongodb exists,id="+id);
			mongodb.update(projectDetail);
		}
		// 不存在，就增加
		else {
			log.info("Update ProjectDetail,Mongodb not exists,id="+id);
			mongodb.add(projectDetail);
		}
		
		// hbase增加和更新是同一个接口
		//log.info("Update ProjectDetail for hbase,id="+id);
		//hbase.insertProjectDetail(projectDetail);
	}

	// 2个都查询，优先使用Mongodb
	public ProjectDetail get(long id) {
		ProjectDetail one = null;
		ProjectDetail hbaseOne = null;//hbase.getProjectDetail(id);
		ProjectDetail mongodbOne = mongodb.get(id);
		if (mongodbOne != null) {
			one = mongodbOne;
			//log.info("Project Detail,Mongodb exists,Use Mongodb," + one);
		} else if (hbaseOne != null) {
			one = hbaseOne;
			log.info("Project Detail,Mongodb not exists,Use Hbase," + one);
			log.info("Add Project Detail To Mongodb");
			// 同步Hbase中的数据到Mongodb
			mongodb.add(hbaseOne);
		}
		return one;
	}

	// 2个都查询，优先使用Mongodb
	public List<ProjectDetail> getProjectInfoBasic(List<Long> idList) {
		List<ProjectDetail> list = null;
		List<ProjectDetail> hbaseList = null;//hbase.getProjectInfoBasic(idList);
		List<ProjectDetail> mongodbList = mongodb.getProjectInfoBasic(idList);
		// 优先使用Mongodb中的,条件，Mongodb中的个数不小于hbase中的
		if (mongodbList != null) {
			int size = mongodbList.size();
			if (hbaseList == null || hbaseList.size() <= size) {
				list = mongodbList;
				log.info("ProjectDetail list,Use MongodbList,size=" + size);
			}else{
				list = hbaseList;
				log.info("ProjectDetail list,Use HbaseList,size=" + hbaseList.size()+",mongodb count "+size+" < hbase count "+hbaseList.size());
			}
		}
		// 其次使用Hbase中的，不会同步hbase中的数据到Mongodb
		else if (hbaseList != null) {
			list = hbaseList;
			log.info("ProjectDetail list,Use HbaseList,size=" + hbaseList.size());
		}
		return list;
	}
}
